// 操作人ID
var operateUserId = JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID;
//操作人姓名
var operateUserName = JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name;
//操作人帐号
var operateAccountName = JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.username;

// 客户组ID
var mainCustomerId = sessionStorage.getItem("mainCustomerId")

//页大小
var pageSize = 50;

/*重点商品列表*/

$(function () {
    //绑定所属渠道下拉列表
    allChannelConfig();
})

//获取光标
$("#class1").focus(function () {
    $("#classUl1").show();
    goods_listCategory(1);
});

// 关联弹框
function relevanceProduct_Dialogs (id, skuCode) {
    $("input[name='channelImportantSkuId']").val(id);
    $("input[name='relevance-skuCode']").val(skuCode);
    $("#relevance-pro-info").html("");
    $('#normal').modal('show')
}

//获取关联商品信息
function relevanceProduct () {
    $("#relevance-pro-info").html("");
    var customerId = $("select[name='customerId']").val();
    if (customerId == "0") {
        $.Huimodalalert('请选择渠道商', 2000);
        return false;
    }

    var skuCode = $("input[name='relevance-skuCode']").val();
    if (skuCode == null || skuCode == "") {
        $.Huimodalalert('SKU码不能为空', 2000);
        return false;
    }
    var param = {
        skuCode: skuCode,
        customerId: customerId
    }
    $.ajax({
        url: root.dockingplatform.queryChannelSkuBySkuCode,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(param),
        success: function (result) {
            console.log(result);
            if (result.errorCode == 0) {
                if (result.data == null) {
                    $.Huimodalalert("返回SKU信息为空", 2000);
                } else {
                    $("#relevance-pro-info").html(result.data.compoundName);
                }
            } else {
                $.Huimodalalert(result.msg, 2000);
            }
        },
        error: function () {
            $.Huimodalalert('提交失败！', 2000);
        }
    });
}

//提交关联sku信息
function submit_RelevanceProduct () {
    var customerId = $("select[name='customerId']").val();
    if (customerId == "0") {
        $.Huimodalalert('请选择渠道商', 2000);
        return false;
    }

    var skuCode = $("input[name='relevance-skuCode']").val();
    if (skuCode == null || skuCode == "") {
        $.Huimodalalert('SKU码不能为空', 2000);
        return false;
    }

    var proInfo = $("#relevance-pro-info").html();
    if (proInfo == "") {
        $.Huimodalalert('请获取商品名称后提交', 2000);
        return false;
    }

    var p_json = {
        customerId: customerId,
        channelImportantSkuId: $("input[name='channelImportantSkuId']").val(),
        skuCode: skuCode,
        operator: operateUserName
    }
    $.ajax({
        url: root.dockingplatform.channelImportantRelationSku,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(p_json),
        success: function (result) {
            if (result.errorCode == 0) {
                $.Huimodalalert('提交成功！', 2000);
                $('#normal').modal('hide');
                focusProcurePageList();
            }
            else {
                $.Huimodalalert("'提交失败" + result.msg, 2000);
            }
        },
        error: function () {
            $.Huimodalalert('提交失败！', 2000);
        }
    });
}

//解除关联SKU信息
function remove_relevanceProduct (id, skuName) {
    var customerId = $("select[name='customerId']").val();

    var p_json = {
        customerId: customerId,
        channelImportantSkuId: id,
        skuCode: "",
        operator: operateUserName
    }

    layer.open({
        type: 1,
        title: "提示",
        offset: "auto",
        content: "<div style='margin: 20px;'>请确认将" + skuName + "商品名称解绑</div>",
        area: "620px",
        btn: ["确认", "取消"],
        btnAlign: "c",
        yes: function () {
            layer.close(layer.index);
            $.ajax({
                url: root.dockingplatform.channelImportantRelationSku,
                cache: false,  //禁用缓存
                type: "POST",
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(p_json),
                success: function (result) {
                    if (result.errorCode == 0) {
                        $.Huimodalalert('解除成功！', 2000);
                        $('#normal').modal('hide');
                        focusProcurePageList();
                    }
                    else {
                        $.Huimodalalert("'提交失败" + result.msg, 2000);
                    }
                },
                error: function () {
                    $.Huimodalalert('提交失败！', 2000);
                }
            });
        },
        cancel: function () {

        },
    });
}

//绑定所属渠道下拉列表
function allChannelConfig () {
    $.ajax({
        type: "post",
        url: root.dockingplatform.allChannelConfig,
        cache: false,
        dataType: "json",
        success: function (data) {
            if (data.errorCode == "0") {
                var content = "";
                data.data.forEach(function (value, index, array) {
                    content += "<option value='" + value.customerId + "'>" + value.customerName + "</option>";
                });
                $("#customerId").append(content);
            }
        },
        error: function () {
            $.Huimodalalert('获取所属渠道信息失败', 2000);
        }
    });
}



$(document).bind("click", function (e) {
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if ($(e.target).closest("#classUl1").length == 0 && $(e.target).closest("#class1").length == 0) {
        //点击id为menu之外且id不是不是open，则触发
        $("#classUl1").hide()
        $("#class2").val();

    }
});

//渠道重点商品明细-详情页面
function relevanceSkuDetailPage (title, url, id, customerId) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);

    sessionStorage.setItem("channelImportantSkuId", id);
    sessionStorage.setItem("customerId", customerId);
}

function goods_listCategory (categoryLevel) {
    console.log($("#class1").val())
    var categoryName = $("#class1").val();
    var user_data = {
        categoryLevel: categoryLevel,
        categoryName: $("#class1").val(),
    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if (data.errorCode == "0") {
            if (data.data == null) {
                classStr = "<li>无数据</li>"
                $("#classUl1").html(classStr);
            } else {
                var classStr = "";
                for (var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
                $("#classUl1").html(classStr);
            }
        }
    }
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

function nextClass (category_id, level, category_name) {
    $("#class" + level + "").val(category_name);
    if (level == 1) {
        firstCategoryId = category_id;
        $("#class2").val("");
        $("#class3").val("");
    } else if (level == 2) {
        secondCategoryId = category_id;
        $("#class3").val("");
    } else if (level == 3) {
        $("#class3").attr("data-CategoryId", category_id);
    }
    var user_data = {
        parentCateId: category_id,
    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if (data.errorCode == "0") {
            if (data.data == null) {
                classStr = "<li>无数据</li>";
            } else {
                var classStr = "";
                for (var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
            }
            if (data.data[0] == undefined) {
                classValue = category_id;
                var nextLevel = level + 1;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + level + "").hide();
            } else {
                var nextLevel = data.data[0].category_level;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + nextLevel + "").show();
                $("#classUl" + level + "").hide()
            }
        }
    }
    getNext_input(level + 1, category_id);
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

// 2,3,4级的模糊查询
function getNext_input (level, category_id) {
    if (level == 4) {
        goodslist_cantegory_id = category_id;
        thirdCategoryId = category_id;
    }
    if (level < 4) {
        console.log(level)
        $("#class" + level + "")[0].oninput = function () {
            var user_data = {
                parentCateId: category_id,
                categoryName: $("#class" + level + "").val()
            }
            var succCallBack = function (data, status, response) {
                if (data.errorCode == 0) {
                    if (data.data == null) {
                        classStr = "<li>无数据</li>";
                    } else {
                        var classStr = "";
                        for (var i = 0; i < data.data.length; i++) {
                            classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                        }
                    }
                    if (data.data[0] == undefined) {
                        classValue = category_id;
                        var nextLevel = level + 1;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").hide();
                    } else {
                        var nextLevel = data.data[0].category_level;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").show();
                    }
                }
            }
            web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
        }
        //获取光标
        $("#class" + level + "").focus(function () {
            $("#classUl" + level + "").show();
        });
        $(document).bind("click", function (e) {
            //id为menu的是菜单，id为open的是打开菜单的按钮
            if ($(e.target).closest("#classUl" + level + "").length == 0 && $(e.target).closest("#class" + level + "").length == 0) {
                //点击id为menu之外且id不是不是open，则触发
                $("#classUl" + level + "").hide()
            }
        });
    }

}

var focusProcure_DataSource = [];

//重点商品池-列表
function focusProcurePageList () {
    var customerId = $("select[name='customerId']").val();
    if (customerId == "0") {
        $.Huimodalalert('请选择渠道商', 2000);
        return false;
    }
    var categoryId = $("input[name='class3']").attr("data-CategoryId");
    var json = {
        pageNo: 1,
        pageSize: pageSize,
        customerId: customerId,
        skuCode: $("input[name='skuCode']").val(),
        skuName: $("input[name='skuName']").val(),
        categoryId: categoryId,//三级类目
        relationStatus: $("select[name='relationStatus']").val(),//关联状态
        channelInBoundStatus: $("select[name='channelInBoundStatus']").val(),//渠道入库状态
        channelState: $("select[name='channelState']").val()        //渠道上下架状态
    }
    $.ajax({
        url: root.dockingplatform.queryAddressConfigDetails,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(json),
        success: function (result) {
            $("input[name='pageNum']").val(result.data.pageNum);
            initDataTable_Shield(result);
            $('.M-box3').pagination({
                pageCount: result.data.pages,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    json.pageNo = api.getCurrent();
                    $.ajax({
                        url: root.dockingplatform.queryAddressConfigDetails,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify(json),
                        success: function (result) {
                            $("input[name='pageNum']").val(result.data.pageNum);
                            initDataTable_Shield(result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
}

//重点商品池-渲染列表+分页
function initDataTable_Shield (dataSource) {
    var dttable = $('#shanDataTable').dataTable(); // 初始化dataTable，清空上一个值
    dttable.fnClearTable(); //清空一下table
    dttable.fnDestroy(); //还原初始化了的datatable
    $("#shanDataTable").DataTable({
        "order": [[1, "desc"]],
        "autoWidth": false,
        "ordering": false,
        "searching": false,
        "paging": false,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": true,
        "aLengthMenu": [5, 10, 25, 50],
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />",
        },
        data: dataSource.data.list,
        columnDefs: [
            {
                "render": function (data, type, row, meta) {
                    var val = row.id
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row.channelSkuCode
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 1
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row.channelSkuName
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 2
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row.channelModel
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 3
            },
            {
                "render": function (data, type, row) {
                    var val = row.channelBrand
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 4
            },
            {
                "render": function (data, type, row) {
                    var val = row.channelPrice
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 5
            },
            {
                "render": function (data, type, row) {
                    var val = row.channelCategoryName
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 6
            },
            {
                "render": function (data, type, row) {
                    var val = row.channelState
                    if (val == undefined) {
                        val = ''
                    }
                    if (val == "1") {
                        val = "上架";
                    } else if (val == "0") {
                        val = "下架";
                    }
                    return val;
                },
                "targets": 7
            },
            {
                "render": function (data, type, row) {
                    var val = row.channelInBoundStatus
                    if (val == undefined) {
                        val = ''
                    }
                    switch (val) {
                        case 0:
                            val = "";
                            break;
                        case 1:
                            val = "已入库";
                            break;
                        case 2:
                            val = "<div style=\"position: relative;\" ><span style=\"color: red;\" onmouseover=\"javascript:$('#channelFailReason" + row.id + "').show();\" onmouseout=\"javascript:$('#channelFailReason" + row.id + "').hide();\">入库失败</span><div id='channelFailReason" + row.id + "' class=\"channelFailReason-text\">" + row.channelFailReason + "</div></div>";
                            break;
                    }
                    return val;
                },
                "targets": 8
            },
            {
                "render": function (data, type, row) {
                    var val = row.skuCode
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 9
            },
            {
                "render": function (data, type, row) {
                    var val = row.skuName
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 10
            },
            {
                "render": function (data, type, row) {
                    var val = row.specifications
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 11
            },
            {
                "render": function (data, type, row) {
                    var val = "<a href='javascript:0;' onclick=\"relevanceProduct_Dialogs(" + row.id + ",'" + row.skuCode + "')\">关联</a> ";
                    val += " <a href = 'javascript:0;' onclick=\"relevanceSkuDetailPage('查看详情','focusProcure_Details.html'," + row.id + ",'" + row.customerId + "')\" >查看详情</a> ";
                    val += " <a href = 'javascript:0;' onclick=\"remove_relevanceProduct(" + row.id + ",'" + row.skuName + "')\" >解绑</a>";
                    return val;
                },
                "targets": 12
            },
        ]
    });
};

//下载渠道重点商品列表清单
function exportChannelImportantSkuList () {
    var customerId = $("select[name='customerId']").val();
    var categoryId = $("input[name='class3']").attr("data-CategoryId");
    var pageNo = $("input[name='pageNum']").val();
    var skuCode = $("input[name='skuCode']").val();
    var skuName = $("input[name='skuName']").val();
    var relationStatus = $("select[name='relationStatus']").val();//关联状态
    var channelInBoundStatus = $("select[name='channelInBoundStatus']").val();//渠道入库状态
    var channelState = $("select[name='channelState']").val();        //渠道上下架状态

    var param = "?pageNo=" + pageNo + "&pageSize=" + pageSize + "&customerId=" + customerId;
    param += "&categoryId=" + categoryId + "&skuCode=" + skuCode + "&skuName=" + skuName + "&relationStatus=" + relationStatus;
    param += "&channelInBoundStatus=" + channelInBoundStatus + "&channelState=" + channelState;

    window.location.href = root.dockingplatform.exportChannelImportantSkuList + param;
}

//下载渠道重点商品关联模板
function downloadImportantSkuRelationExcelTemplate () {
    window.location.href = root.dockingplatform.downloadImportantSkuRelationExcelTemplate;
}

//批量导入重点商品关联关系
function importChannelImportantSkuRelationByExcel () {
    var name = $("#file").val()
    var result = /\.[^\.]+/.exec(name);
    if (result != ".xlsx" && result != ".xls") {
        $.Huimodalalert('格式不正确！', 2000);
        return false;
    }
    var customerId = $("select[name='customerId']").val();
    var formData = new FormData();
    formData.append('customerId', customerId);
    formData.append('file', $("#file")[0].files[0]);
    formData.append('operateUserName', operateUserName);
    $.ajax({
        url: root.dockingplatform.importChannelImportantSkuRelationByExcel,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data)
            $('#file').val('');
            if (data.errorCode == 0) {
                $.Huimodalalert('导入成功', 2000);
                if (customerId != "0") {
                    focusProcurePageList();
                }
            } else {
                $.Huimodalalert(data.msg, 2000);
            }
        }
    });
}

//查询最后一次重点商品关联报告批次号
function selectLatestBatchNo () {
    var customerId = $("select[name='customerId']").val();
    if (customerId == "0") {
        $.Huimodalalert('请选择渠道商', 2000);
        return false;
    }
    //todo 用公共ajax
    $.ajax({
        url: root.dockingplatform.selectLatestBatchNo,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({ "customerId": customerId }),
        success: function (result) {
            if (result.errorCode == 0) {
                if (result.data != null && result.data != "") {
                    exportImportantSkuRelation(customerId, result.data);
                } else {
                    $.Huimodalalert("报告未生成" + result.sub_msg, 2000);
                    return false;
                }
            } else {
                $.Huimodalalert("调用成功,返回错误" + result.sub_msg, 2000);
                return false;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

//导出报告
function exportImportantSkuRelation (customerId, batchNo) {
    var param = "?customerId=" + customerId + "&batchNo=" + batchNo;
    window.location.href = root.dockingplatform.exportImportantSkuRelation + param;
}

